﻿var ly_index;
var objResult = null;

function Is_Num(input_value) {
    var ival = parseInt(input_value);
    if (isNaN(ival)) {
        return -1;
    } else {
        return ival;
    }
}

/************************************/
function exportJson2Excel(json, type) {
    //TODO 记录导出操作日志
    var log = {
        "type": "json2excel"
    };
    //title
    try {
        var title = new Set();
        for (var i = 0; i < json.length; i++) {
            var r = json[i];
            getProFromObject(r, title);
        }
        console.log("title", title);

        var data = [];
        for (var i = 0; i < json.length; i++) {
            var r = json[i];
            var dataRow = [];
            title.forEach(function (t) {
                var d1 = r[t];
                var ss = t.split(".");
                if (ss.length >= 2) {
                    var tmp = r;
                    for (var i = 0; i < ss.length; i++) {
                        var s = ss[i];
                        tmp = tmp[s];
                        if (!tmp) {
                            break;
                        }
                    }
                    d1 = tmp;
                }
                if (d1) {
                    if (typeof d1 == 'object') {
                        dataRow.push(JSON.stringify(d1));
                    } else {
                        dataRow.push(d1);
                    }

                } else {
                    dataRow.push("");
                }

            });

            data.push(dataRow);
        }
        console.log("data", data);
        jsonToExcelConvertor(data, 'Report', Array.from(title), type);
    } catch (err) {
        console.error(err);
        alert("导出报错：" + err.stack);
        log.error = err.stack;
        log.json = json;
    }
    finally {
        /*
        OplogsService.save(log).$promise.then(function(res) {
        console.log(res);
        }).
        catch(function(error) {
        console.log(error);
        alert("系统错误:" + JSON.stringify(error));
        });*/
    }
}
function getProFromObject(r, title, parentsPros) {
    for (var rp in r) {
        if (parentsPros) {
            title.add(parentsPros + "." + rp);
        } else {
            title.add(rp);
        }
        if (typeof r[rp] == 'object') {
            if (parentsPros) {
                getProFromObject(r[rp], title, parentsPros + "." + rp);
            } else {
                getProFromObject(r[rp], title, rp);
            }

        }
    }
}
function jsonToExcelConvertor(JSONData, FileName, ShowLabel, type) {
    type = type ? type : "xls";
    var application = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    if (type == "xls") {
        application = "application/vnd.ms-excel";
    }

    // 先转化json
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var excel = '<table>';

    // 设置表头
    var rr = '<tr>';
    for (var j = 0,
        l = ShowLabel.length; j < l; j++) {
        rr += '<td>' + ShowLabel[j] + '</td>';
    }

    // 换行
    excel += rr + '</tr>';

    // 设置数据
    for (var i = 0; i < arrData.length; i++) {
        var row = '<tr>';

        for (var index = 0; index < arrData[i].length; index++) {
            var value = arrData[i][index] === '.' ? '' : arrData[i][index];
            row += '<td>' + value + '</td>';
        }

        excel += row + '</tr>';
    }

    excel += '</table>';

    var excelFile = '<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:x=\'urn:schemas-microsoft-com:office:excel\' xmlns=\'http://www.w3.org/TR/REC-html40\'>';
    excelFile += '<meta http-equiv="content-type" content="' + application + '; charset=UTF-8">';
    excelFile += '<meta http-equiv="content-type" content="' + application;
    excelFile += '; charset=UTF-8">';
    excelFile += '<head>';
    excelFile += '<!--[if gte mso 9]>';
    excelFile += '<xml>';
    excelFile += '<x:ExcelWorkbook>';
    excelFile += '<x:ExcelWorksheets>';
    excelFile += '<x:ExcelWorksheet>';
    excelFile += '<x:Name>';
    excelFile += '{worksheet}';
    excelFile += '</x:Name>';
    excelFile += '<x:WorksheetOptions>';
    excelFile += '<x:DisplayGridlines/>';
    excelFile += '</x:WorksheetOptions>';
    excelFile += '</x:ExcelWorksheet>';
    excelFile += '</x:ExcelWorksheets>';
    excelFile += '</x:ExcelWorkbook>';
    excelFile += '</xml>';
    excelFile += '<![endif]-->';
    excelFile += '</head>';
    excelFile += '<body>';
    excelFile += excel;
    excelFile += '</body>';
    excelFile += '</html>';

    var uri = 'data:' + application + ';charset=utf-8,' + encodeURIComponent(excelFile);

    var link = document.createElement('a');
    link.href = uri;
    //TODO Cannot set property style of #<HTMLElement> which has only a getter
    // link.style = 'visibility:hidden';
    $(link).css("visibility", "hidden");
    // link.download = FileName + '.'+type;
    $(link).attr("download", FileName + '.' + type);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/************************************/
function cloneAndConvert(sourceDate, fileName) {
    var jsonData = sourceDate || [];
    var filteredGridData = JSON.parse(JSON.stringify(jsonData));
    JSONToCSVConvertor(filteredGridData, fileName, true);
}

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {

    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    //this trick will generate a temp "a" tag
    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);

    var csv = CSV;
    blob = new Blob([csv], {
            type: 'text/csv'
        });
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename = ReportTitle || 'UserExport.csv';
    $("#lnkDwnldLnk").attr({
        'download': filename,
        'href': csvUrl
    });

    $('#lnkDwnldLnk')[0].click();
    document.body.removeChild(link);
}
/************************************/

$(document).ready(function () {
	init_page();
    ly_index = layer.load();
    $("#param_name").val("APP_USER_ZXY");

    rowid = $("#table_list_1", window.parent.document).jqGrid("getGridParam", "selrow");
    if (typeof(rowid) != "undefined") {
        rowData = $('#table_list_1', window.parent.document).jqGrid('getRowData', rowid);
        $("#param_value1").val(rowData.PAGE_CODE);
    }

    rowid = $("#table_list_5", window.parent.document).jqGrid("getGridParam", "selrow");
    if (typeof(rowid) != "undefined") {
        rowData = $('#table_list_5', window.parent.document).jqGrid('getRowData', rowid);
        $("#sub_code").val(rowData.SUB_CODE);
    }

    rowid = $("#table_list_6", window.parent.document).jqGrid("getGridParam", "selrow");
    if (typeof(rowid) != "undefined") {
        rowData = $('#table_list_6', window.parent.document).jqGrid('getRowData', rowid);
        $("#sub_usercode").val(rowData.SUB_USERCODE);
    }

    var rows = $("#table_list_2", window.parent.document).jqGrid("getRowData");
    for (var i = 1; i <= rows.length; i++) {
        var ary_para_value = rows[i - 1].URL_IN_PARAM.split(",");
        for (var j = 0; j < ary_para_value.length; j++) {
            var iIndex = Is_Num(ary_para_value[j].replace("param_value", ""));
            if (iIndex != -1 && $("#param_value" + iIndex).length == 0) {
                var input_prarm_value = "<div class=\"form-group\"><label class='col-sm-3 control-label'>输入参数" + iIndex.toString() + "(param_value" + iIndex.toString() + "=)</label>"
                     + "<div class='col-sm-8'>"
                     + "<input id='param_value" + iIndex.toString() + "' placeholder='请输入参数' name='param_value" + iIndex.toString() + "' type='text' class='form-control' >"
                     + "</div></div>";
                $("#param_values").append(input_prarm_value);
            }
        }
    }

    //$("#btnJsonToExcel").click(function(){
    //	exportJson2Excel(objResult,"xls");
    //cloneAndConvert(objResult,"123.xls");
    //});

    $("#btnDebug").click(function () {
        $("#debug_result").val("");
        ly_index = layer.load();
        var show_url = "http://" + getIP_Url() + "?sub_code=" + $("#sub_code").val() + "&sub_usercode=" + $("#sub_usercode").val()+"&session_id="+session_id;
        var rooturl = show_url + "&param_name=" + $("#param_name").val();
        var rows = $("#table_list_2", window.parent.document).jqGrid("getRowData");
        var source_code = "<script type=\"text/javascript\">\r\n"
             + "	$.ajax({\r\n"
             + "		type: \"POST\",\r\n"
             + "		async: false,\r\n"
             + "		url: \"" + show_url + "\",\r\n"
             + "		data:{param_name:\"" + $("#param_name").val() + "\"\r\n";
        //+"			,sub_code:\""+$("#sub_code").val()+"\"\r\n"
        //+"			,sub_usercode:\""+$("#sub_usercode").val()+"\"\r\n";
        for (var i = 1; i < 100; i++) {
            if ($("#param_value" + i.toString()).length == 0)
                break;
            else {
                rooturl += "&param_value" + i.toString() + "=" + $("#param_value" + i.toString()).val();
                source_code += "			,param_value" + i.toString() + ":\"" + $("#param_value" + i.toString()).val() + "\"\r\n";
            }
        }

        /*
        for(var i = 1; i <= rows.length; i ++){
        rooturl += "&param_value"+i.toString()+"="+$("#param_value"+i.toString()).val();
        source_code +="			,param_value"+i.toString()+":\""+$("#param_value"+i.toString()).val()+"\"\r\n"
        }*/
        source_code += "},\r\n"
         + "		//跨域请求的URL\r\n"
         + "		dataType: \"jsonp\",\r\n"
         + "		jsonp: \"jsoncallback\",\r\n"
         + "		jsonpCallback: \"data_result\",\r\n"
         + "		success: function(data) {\r\n"
         + "		},\r\n"
         + "		error: function() {\r\n"
         + "		if(confirm(\"网络故障，请刷新网络\"))\r\n"
         + "			window.location.reload();\r\n"
         + "		},\r\n"
         + "		// 请求完成后的回调函数 (请求成功或失败之后均调用)\r\n"
         + "		complete: function(XMLHttpRequest, textStatus) {\r\n"
         + "		}\r\n"
         + "	});\r\n"
         + "\r\n"
         + "	function data_result(input_data)\r\n"
         + "	{\r\n"
         + "		//alert(input_data);\r\n"
         + "		alert(JSON.stringify(input_data));\r\n"
         + "	}\r\n"
         + "</script>";
        $("#t_proc_name_url").val(rooturl);
        $("#view_source").val(source_code);

        $.ajax({
            type: "POST",
            async: false,
            url: rooturl,
            data: {},
            //跨域请求的URL
            dataType: "jsonp",
            jsonp: "jsoncallback",
            jsonpCallback: "s_debug_result",
            success: function () {},
            error: function () {
                layer.close(ly_index);
                swal({
                    title: "告警",
                    text: "网络异常或系统故障，请刷新页面！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "刷新",
                    closeOnConfirm: false
                },
                    function () {
                    window.location.reload();
                })
            },
            // 请求完成后的回调函数 (请求成功或失败之后均调用)
            complete: function (XMLHttpRequest, textStatus) {}
        });
    });
    layer.close(ly_index);
    return false;
});

function s_debug_result(input) {
    objResult = input.APP_USER_ZXY;
    $("#debug_result").val(JSON.stringify(input));
    layer.close(ly_index);
}
